package com.lghs.stutor;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;

public class Login extends Activity implements Alertresponder {

    // Global variables
    ProgressDialog pDialog;
    static String url, username, password, type, email;
    static String alerttitle, alertmessage, alertposbutton, alertneubutton,
            alertnegbutton, buttonamount, buttonreason;
    EditText inputusername, inputpassword;
    Vital vital = new Vital();
    HttpGet httpGet;
    HttpResponse execute;
    DefaultHttpClient client;
    InputStream content;
    Intent i;
    InputMethodManager inputManager;
    Bundle b;
    ConnectivityManager cm;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);
        declaredcomponents();
        onclicklisteners();
    }

    public void declaredcomponents() {
        inputusername = (EditText) findViewById(R.id.login_edittext_username);
        inputpassword = (EditText) findViewById(R.id.login_edittext_password);
    }

    public void onclicklisteners() {
        final Button loginbutton = (Button) findViewById(R.id.login_button_login);
        loginbutton.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                userlogin();
            }
        });
        final TextView createbutton = (TextView) findViewById(R.id.login_textview_createaccount);
        createbutton.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                createaccount();
            }
        });
        final TextView forgotpassword = (TextView) findViewById(R.id.login_textview_recoverpassword);
        forgotpassword.setOnClickListener(new View.OnClickListener() {
            public void onClick(View view) {
                forgotpass();
            }
        });
    }

    public void userlogin() {
        inputManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
        if (inputManager.isAcceptingText())
            inputManager.hideSoftInputFromWindow(getCurrentFocus()
                    .getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
        cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
        vital.checkInternetConnection(Login.this, cm);
    }

    public void onBackPressed() {
        finish();
    }

    public void buttonhandler(int number) {
        switch (number) {
            case 1:
                userlogin();
                break;
            case 2:
                createaccount();
                break;
        }
    }

    @Override
    public void internethandler(int number) {
        switch (number) {
            case 1:
                username = inputusername.getText().toString();
                password = inputpassword.getText().toString();
                new checklogin().execute();
                break;
            case 2:
                vital.alertsystem(Login.this, "Internet Connectivity",
                        "Your internet connection seems to be missing", "13",
                        "red", "Try Again", "", "Cancel");
                break;
        }
    }

    public void createaccount() {
        i = new Intent(getApplicationContext(), Create.class);
        startActivity(i);
        finish();
    }

    public void forgotpass() {
        i = new Intent(getApplicationContext(), RecoverPass.class);
        startActivity(i);
        finish();
    }

    private int checkInternetConnection() {
        ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
        if (cm.getActiveNetworkInfo() != null
                && cm.getActiveNetworkInfo().isAvailable()
                && cm.getActiveNetworkInfo().isConnected()) {
            if (vital.logthekitty)
                Log.v("Network Status: ", "Internet Connection Present");
            return 1;
        } else {
            if (vital.logthekitty)
                Log.v("Network Status: ", "Internet Connection Not Present");
            return 2;
        }
    }

    private class checklogin extends AsyncTask<String, String, String> {
        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            pDialog = new ProgressDialog(Login.this, R.style.Theme_MyDialog);
            pDialog.setTitle("You will now wait!");
            pDialog.setIcon(R.drawable.idk);
            pDialog.setMessage("Logging in\nPlease Wait..");
            pDialog.setIndeterminate(false);
            pDialog.setCancelable(true);
            pDialog.show();
        }

        protected String doInBackground(String... urls) {
            String response = "";
            url = "http://" + vital.host + "/login.php?u=" + username + "&p="
                    + password + "";

            try {
                client = new DefaultHttpClient();
                httpGet = new HttpGet(url);
                execute = client.execute(httpGet);
                content = execute.getEntity().getContent();

                BufferedReader buffer = new BufferedReader(
                        new InputStreamReader(content));
                String s = "";
                while ((s = buffer.readLine()) != null) {
                    response += s;
                }
                type = "student";
                url = "http://" + vital.host + "/type.php?u=" + username
                        + "&p=" + password + "&t=" + type + "";
                httpGet = new HttpGet(url);
                execute = client.execute(httpGet);
                content = execute.getEntity().getContent();

                BufferedReader buffer_checklogin = new BufferedReader(
                        new InputStreamReader(content));
                execute = client.execute(httpGet);
                while ((s = buffer_checklogin.readLine()) != null) {
                    response += s;
                }

            } catch (Exception e) {
                if (vital.logthekitty)
                    Log.v("Bad info", e.getMessage());
                e.printStackTrace();
            }
            return response;
        }

        @Override
        protected void onPostExecute(String result) {

            if (result.contains("Verified")) {
                Intent i = new Intent(getApplicationContext(), Home.class);
                i.putExtra("uname", username);
                startActivity(i);
                pDialog.dismiss();
                finish();
            } else {
                if (vital.logthekitty)
                    Log.v("Incorrect Login", "Invalid Login Information");
                vital.alertsystem(
                        Login.this,
                        "Error: #1",
                        "The account information used is either incorrect or nonexistant.",
                        "123", "red", "Try Again", "Create\nAccount",
                        "Cancel");
            }
            pDialog.dismiss();
        }
    }

}